import React, {useEffect} from 'react';
import {useRef, useState} from 'react';
import {
    ShopOutlined, UserOutlined, LogoutOutlined, BookOutlined,
    HomeOutlined, AlertOutlined, CloudDownloadOutlined, ProjectOutlined, GatewayOutlined,
    DownOutlined, EditOutlined, ReadOutlined, ContainerOutlined, ShoppingCartOutlined
} from '@ant-design/icons';
import {Button, Menu, message, Input, Dropdown, Space, Modal, Form, Switch, Image, Avatar, Tooltip} from 'antd';
import classes from './index.module.scss'
import {useLocation, useNavigate} from "react-router-dom";
import {useDispatch, useSelector} from "react-redux";
import {clearUserAllInfo, updateUserAllInfo, userLogin, userRegister} from "../../../store/userSlice";
import history from "../../../utils/history";
import logo from '../../../assets/logo192.png'
import {getToken, removeToken} from "../../../utils/token";
import '../../../assets/font/vip/iconfont'
import '../../../assets/font/vip/iconfont.css'
import {debounce} from "lodash";
import {getArticleIntro, updateArticleList} from "../../../store/frontDesk/articleSlice";
import {reqArticleIntro, reqGetNoteList, reqWriteNode} from "../../../api/frontDesk/frontDeskApi";
import MyQuill from "../../myQuill";
import LoginAlert from "../../LoginAlert";


//导航的item项
const menuItems = [
    {label: '首页', icon: <HomeOutlined/>, key: '/'},
    {label: '下载', icon: <CloudDownloadOutlined/>, key: '/download'},
    {label: '课程', icon: <ProjectOutlined/>, key: '/course'},
    {label: '活动', icon: <GatewayOutlined/>, key: '/activity'},
    {label: '社区', icon: <AlertOutlined/>, key: '/community'},
    {label: '商城', icon: <ShopOutlined/>, key: '/shopping'}
];


// 下拉菜单项
const handlerItems = [
    {label: '写文章', key: '/write-article', icon: <EditOutlined/>},
    {label: '写笔记', key: '/write-node', icon: <ReadOutlined/>},
    {label: '草稿箱', key: '/my-draft', icon: <ContainerOutlined/>},
];

//用户操作
const userChooseItems = [
    {label: '个人中心', key: '/user-center', icon: <UserOutlined/>},
    {label: '课程中心', key: '/my-course', icon: <BookOutlined/>,},
    {label: '参与活动', key: '/my-activity', icon: <GatewayOutlined/>},
    {label: '我的商品', key: '/my-cart', icon: <ShoppingCartOutlined/>},
    {label: '退出登录', key: '/logOut', icon: <LogoutOutlined/>},
];
//手机号校验规则
const phoneRules = [{
    type: "string",
    required: true,
    len: 11,
    message: '请输入11位的手机号!'
}]
//昵称校验规则
const nicknameRules = [{
    type: "string",
    required: true,
    message: '请输入昵称!'
}]
//密码校验规则
const passwordRules = [{
    type: "string",
    required: true,
    min: 6,
    max: 15,
    message: '请输入6-15位的密码!'
}]

const FrontDeskMenu = () => {
    const token = getToken()
    const nav = useNavigate()
    const dispatch = useDispatch()

    const {Search} = Input;
    const {pathname} = useLocation()
    //会员状态
    const [vip, setVip] = useState(null)
    //使菜单项高亮
    const [current, setCurrent] = useState(pathname);

    const [loadings, setLoadings] = useState([]);
    const {persistedReducer} = useSelector(state => state)
    const {userAllInfo} = persistedReducer.user
    //弹出登录的对话框逻辑
    const [loginOpen, setLoginOpen] = useState(false);
    const [registerOpen, setRegisterOpen] = useState(false);
    //弹出写笔记的对话框
    const [noteOpen, setNoteOpen] = useState(false);

    const [open, setOpen] = useState(false);

    //传递一个文章内容给子组件
    const [content, setContent] = useState('')
    const [title, setTitle] = useState('')
    const contentChange = (content) => {
        setContent(content)
    }

    useEffect(() => {
        if (Object.keys(userAllInfo).length !== 0) {
            setVip(userAllInfo.role)
        }
    }, [vip, userAllInfo])
    //导航点击事件
    const menuClick = (menuItem) => {
        setCurrent(menuItem.key)
        history.push(`${menuItem.key}`)
    }
    //搜索逻辑
    const onSearch = debounce(async (e) => {
        nav('/')
        setTimeout(async () => {
            const result = await reqArticleIntro()
            dispatch(updateArticleList(result.articleList.filter((item) => item.title.indexOf(e.target.value) !== -1)))
        }, 500)
    }, 500)

    //弹出登录框
    const showModal = () => {
        setLoginOpen(true);
    };
    const writeNoteOk = async () => {
        const info = {
            content,
            title
        }
        console.log(info)
        if (content === '' && title === '') {
            message.info('请输入笔记内容')
        } else {
            const result = await reqWriteNode({user_id: userAllInfo.id, Info: info})
            if (result.status === 0) {
                setNoteOpen(false)
                message.success('编写笔记成功！')
                const result = await reqGetNoteList({user_id: userAllInfo.id})
                nav('/user-center', {state: {noteList: result.data}})
            } else {
                message.error('编写笔记失败!')
            }
        }

    }

    useEffect(() => {
        if (token) {
            enterLoading(0)
            setTimeout(() => {
                setLoginOpen(false)
                nav(`${pathname}`)
            }, 1200)
        }
    }, [token])

    const onLogin = (userInfo) => {
        //从redux仓库里调用登录逻辑
        //这是一个异步的操作
        console.log(userInfo)
        setVip(userAllInfo.role)
        dispatch(userLogin(userInfo))
        if (!getToken()) {
            setLoginOpen(true)
        }
    }
    //下拉菜单点击事件
    const handleMenuClick = (e) => {
        if (token) {
            if (e.key === '/write-node') {
                setNoteOpen(true)
            } else {
                nav(e.key)
            }
        } else {
            message.info('请先登录')
        }
    }
    //创作者中心操作
    const menuProps = {
        items: handlerItems,
        onClick: handleMenuClick,
    }
    //用户登录之后的操作功能
    const userChooseClick = (e) => {
        if (e.key === '/user-center') {
            nav(`/user-center`, {state: {userAllInfo}})
        } else if (e.key === '/logOut') {
            removeToken()
            setVip(null)
            nav('/')
            window.location.reload()
        } else {
            nav(e.key)
        }
    }
    //用户操作
    const userChooseProps = {
        items: userChooseItems,
        onClick: userChooseClick,
    };

    //登录和注册按钮的加载事件
    const enterLoading = (index) => {
        setLoadings((prevLoadings) => {
            const newLoadings = [...prevLoadings];
            newLoadings[index] = true;
            return newLoadings;
        });
        setTimeout(() => {
            setLoadings((prevLoadings) => {
                const newLoadings = [...prevLoadings];
                newLoadings[index] = false;
                return newLoadings;
            });
        }, 1200);
    };
    //注册按钮事件
    const registerFormRef = useRef()
    const onRegister = (registerInfo) => {
        dispatch(userRegister(registerInfo))
        // console.log(registerInfo)
        enterLoading(0)
        setTimeout(() => {
            setRegisterOpen(false)
            setLoginOpen(true)
        }, 1200)
    }
    //重置表单
    const loginFormRef = useRef()
    const reset = () => {
        loginFormRef.current.resetFields()
    }
    //管理员登录按钮
    const adminLogin = () => {
        nav('/admin/login')
        setLoginOpen(false)
    }


    const gotoVip = () => {
        if (getToken()) {
            history.push('/buy-vip')
        } else {
            setOpen(!open)
        }
    }


    return <>
        <div className={classes.Container}>
            <div className={classes.MenuContainer}>
                <div>
                    <Image style={{width: 60, height: 60}} src={logo} preview={false}/>
                </div>

                {/*顶部导航项*/}
                <>
                    <Menu
                        className={classes.Menu}
                        onClick={menuClick}
                        selectedKeys={[current]}
                        mode="horizontal"
                        items={menuItems}/>
                </>

                {/* 搜索框 */}
                <div>
                    <Search
                        placeholder="请输入想搜索的文章"
                        onChange={onSearch}
                        enterButton
                    >
                    </Search>
                </div>

                {/*下拉菜单*/}
                <Dropdown arrow menu={menuProps} overlayStyle={{zIndex: 1000}}>
                    <Button type={"primary"}>
                        <Space>
                            创作者中心
                            <DownOutlined/>
                        </Space>
                    </Button>
                </Dropdown>


                {/*登录按钮*/}
                <div>
                    <>
                        {
                            getToken() ?
                                <Dropdown arrow menu={userChooseProps} overlayStyle={{zIndex: 1000}}>
                                    <div>
                                        <Avatar style={{cursor: "pointer"}} src={userAllInfo.user_avatar}/>
                                    </div>
                                </Dropdown> :
                                < Button type="link" className={classes.LoginButton} onClick={showModal}>
                                    登录
                                </Button>
                        }
                        {/*用户登录的弹出框*/}
                        <>
                            {/*登录对话框*/}
                            <Modal
                                onCancel={() => setLoginOpen(false)}
                                className={classes.Modal}
                                title={<h2>用户登录</h2>}
                                open={loginOpen}
                                bodyStyle={{height: "260px", padding: "30px 40px"}}
                                footer={null}
                                getContainer={false}
                            >
                                <Form
                                    ref={loginFormRef}
                                    name="loginForm"
                                    labelCol={{span: 6, offset: 0}}
                                    wrapperCol={{span: 16}}
                                    // initialValues={{remember: true}}
                                    onFinish={onLogin}
                                    autoComplete="off"
                                >
                                    <Form.Item
                                        // initialValue={13488888888}
                                        label="手机号"
                                        name="phone"
                                        rules={phoneRules}
                                    >
                                        {/*手机号输入框*/}
                                        <Input maxLength={11} allowClear/>
                                    </Form.Item>
                                    <Form.Item
                                        // initialValue={123456}
                                        label="密码"
                                        name="password"
                                        rules={passwordRules}
                                    >
                                        {/*密码输入框*/}
                                        <Input.Password maxLength={15} minLength={6}/>
                                    </Form.Item>
                                    <Form.Item>
                                        <Button onClick={() => {
                                            setRegisterOpen(true);
                                            setLoginOpen(false)
                                        }} type={"link"}>
                                            还没有账号?点击注册
                                        </Button>
                                    </Form.Item>
                                    <div className={classes.LoginHandler}>
                                        <Form.Item>
                                            <Button type="primary" loading={loadings[0]} htmlType="submit">
                                                登录
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button onClick={reset} style={{marginLeft: 15}} type="primary">
                                                重置
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button
                                                onClick={adminLogin}
                                                type={"link"}>
                                                管理员登录
                                            </Button>
                                        </Form.Item>
                                    </div>
                                </Form>
                            </Modal>
                        </>
                        <>
                            {/*注册对话框*/}
                            <Modal
                                onCancel={() => setRegisterOpen(false)}
                                className={classes.Modal}
                                title={<h2>用户注册</h2>}
                                open={registerOpen}
                                bodyStyle={{height: "300px", padding: "30px 40px"}}
                                footer={null}
                                getContainer={false}
                            >
                                <Form
                                    ref={registerFormRef}
                                    name="registerForm"
                                    labelCol={{span: 7, offset: 0}}
                                    wrapperCol={{span: 16}}
                                    initialValues={{remember: true}}
                                    onFinish={onRegister}
                                    autoComplete="off"
                                >
                                    <Form.Item
                                        // initialValue={13488888888}
                                        label="手机号"
                                        name="phone"
                                        rules={phoneRules}>
                                        {/*手机号输入框*/}
                                        <Input maxLength={11} allowClear/>
                                    </Form.Item>
                                    <Form.Item
                                        // initialValue={13488888888}
                                        label="昵称"
                                        name="nickname"
                                        rules={nicknameRules}>
                                        <Input allowClear/>
                                    </Form.Item>
                                    <Form.Item
                                        // initialValue={123456}
                                        label="密码"
                                        name="password"
                                        rules={passwordRules}
                                    >
                                        {/*密码输入框*/}
                                        <Input.Password maxLength={15} minLength={6}/>
                                    </Form.Item>
                                    <Form.Item
                                        // initialValue={123456}
                                        label="确认密码"
                                        name="confirmPassword"
                                        rules={passwordRules}
                                    >
                                        {/*密码输入框*/}
                                        <Input.Password/>
                                    </Form.Item>
                                    <div className={classes.LoginHandler}>
                                        <Form.Item>
                                            <Button type="primary" loading={loadings[0]} htmlType="submit">
                                                注册
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button onClick={reset} style={{marginLeft: 15}} type="primary">
                                                重置
                                            </Button>
                                        </Form.Item>
                                        <Form.Item>
                                            <Button
                                                onClick={adminLogin}
                                                type={"link"}>
                                                管理员登录
                                            </Button>
                                        </Form.Item>
                                    </div>
                                </Form>
                            </Modal>
                        </>
                    </>
                </div>

                {
                    (vip !== null && getToken() && vip !== '普通用户') ?
                        <Tooltip title={userAllInfo.role}>
                            <svg style={{width: 35, height: 35, cursor: 'pointer'}}
                                 className="icon-VIPti"
                                 aria-hidden="true">
                                <use xlinkHref="#icon-VIPti"></use>
                            </svg>
                        </Tooltip>
                        :
                        <Tooltip title="开通会员">
                            <svg onClick={() => gotoVip()} style={{width: 35, height: 35, cursor: 'pointer'}}
                                 className="icon-yooxi"
                                 aria-hidden="true">
                                <use xlinkHref="#icon-yooxi"></use>
                            </svg>
                            {open && <LoginAlert open={open}/>}
                        </Tooltip>
                }

            </div>
            <Modal
                onCancel={() => setNoteOpen(false)}
                title={<h3>写笔记</h3>}
                open={noteOpen}
                width={800}
                bodyStyle={{
                    height: "350px",
                    padding: "40px",
                    display: 'flex',
                    justifyContent: 'space-around',
                    alignItems: 'center',
                    flexDirection: "column"
                }}
                okText="确认"
                cancelText="取消"
                onOk={() => writeNoteOk()}
                getContainer={false}
            >
                <div style={{display: 'flex', flexDirection: 'unset', width: 300, height: 50}}>
                    <h3>标题</h3>
                    <Input onChange={(e) => setTitle(e.target.value)}/>
                </div>
                <MyQuill
                    width={650} height={200}
                    placeholder="请输入文章内容"
                    content={content}
                    contentChange={contentChange}
                />
            </Modal>
        </div>
    </>
}
export default FrontDeskMenu;